package com.by_man.presenter.menu_activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by man on 2017-03-17.
 */
public class ModifyLoginPasswordActivity extends AppCompatActivity {
    private RequestQueue rQueue;
    private EditText code_old;
    private EditText code_new1;
    private EditText code_new2;
    private Button code_save;
    private CheckBox check;

    private final static int SUCCESS = 0x1;
    private final static int FAIL = 0x2;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_loginpassword);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what) {
                    case SUCCESS:
                        Toast.makeText(ModifyLoginPasswordActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(ModifyLoginPasswordActivity.this, SettingActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        break;
                    case FAIL:
                        Toast.makeText(ModifyLoginPasswordActivity.this, "原始密码错误", Toast.LENGTH_SHORT).show();
                        code_old.requestFocus();
                        break;
                    default:
                        break;
                }
            }
        };
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, SettingActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, SettingActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        code_old=(EditText)findViewById(R.id.code_old);
        code_new1=(EditText)findViewById(R.id.code_new1);
        code_new2=(EditText)findViewById(R.id.code_new2);
        check= (CheckBox) findViewById(R.id.check);
        //是否显示密码
        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(check.isChecked()){
                    code_new1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示
                    code_new2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());  //密码以明文显示
                }else{
                    code_new1.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    code_new2.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        code_save=(Button)findViewById(R.id.code_save);
        code_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String old_code = code_old.getText().toString().trim();
                String new1_code = code_new1.getText().toString().trim();
                String new2_code = code_new2.getText().toString().trim();
                old_code = SharedApplication.MD5("$20160608$" + old_code, 32);
                new1_code = SharedApplication.MD5("$20160608$" + new1_code, 32);
                new2_code = SharedApplication.MD5("$20160608$" + new2_code, 32);

                if (!new1_code.equals(new2_code)) {
                    Toast.makeText(ModifyLoginPasswordActivity.this, "两次新密码输入不相同，请重新输入", Toast.LENGTH_SHORT).show();
                } else {
                    HashMap<String, String> params = new HashMap<>();
                    params.put("token", UserInfos.token);
                    params.put("pastpassword",old_code);
                    params.put("newpassword", new1_code);
                    PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                            IpAddress.Modify_Login_Password, params,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String s) {
                                    try {
                                        JSONObject temp = new JSONObject(s);
                                        boolean isUpdate = temp.getBoolean("isUpdate");
                                        if (isUpdate) {
                                            Message msg = handler.obtainMessage();
                                            msg.what = SUCCESS;
                                            msg.sendToTarget();
                                        } else {
                                           Message msg = handler.obtainMessage();
                                            msg.what = FAIL;
                                            msg.sendToTarget();
                                        }
                                    } catch (JSONException je) {
                                        je.printStackTrace();
                                    }
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("ModifyLoginPWError",volleyError.getMessage(),volleyError);
                                }
                            });
                    rQueue.add(stringRequest);
                }
            }
        });

    }
}
